package culton.android.data;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import culton.android.entity.Cinema;
import culton.android.util.Functions;

public class DataHelper {
	
	private static final String TABLE_NAME = "cinemas";	 
	private Context context;
	private SQLiteDatabase db;
	private DatabaseHelper openHelper;
	private SQLiteStatement insertStmt;
	private static final String INSERT = "insert into "
		+ TABLE_NAME + "(name, address, district, city, state) values (?, ?, ?, ?, ?)";
	
	public DataHelper(Context context) {
		this.context = context;
		this.openHelper = new DatabaseHelper(this.context);
	    this.db = openHelper.getWritableDatabase();
	    this.insertStmt = this.db.compileStatement(INSERT);
	}
	 
	public void close() {
		this.openHelper.close();
	}
	
	public long insert(String name, String address, String district, String city, String state) {
		this.insertStmt.bindString(1, name);
		this.insertStmt.bindString(2, address);
		this.insertStmt.bindString(3, district);
		this.insertStmt.bindString(4, city);
		this.insertStmt.bindString(5, state);
		return this.insertStmt.executeInsert();
	}
	 
	public void deleteAll(String tableName) {
		this.db.delete(tableName, null, null);
	}
	 
	public ArrayList<Cinema> selectAll() {
		ArrayList<Cinema> list = new ArrayList<Cinema>();
		
		Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name", "address", "district", "city", "state" },
				null, null, null, null, "name");
		
		if (cursor.moveToFirst()) {
			do {
				Cinema cinema = new Cinema();
				cinema.setID(Functions.removeSpecialCharacters(cursor.getString(0).replaceAll(" ", "_").toLowerCase()));
				cinema.setName(cursor.getString(0));
				cinema.setStreet(cursor.getString(1));
				cinema.setDistrict(cursor.getString(2));
				cinema.setCity(cursor.getString(3));
				cinema.setState(cursor.getString(4));
				list.add(cinema);
			} while (cursor.moveToNext());
		}
		
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		
		return list;
	}
	
	public boolean exists(String cinemaName) {
		boolean exists = false;
		
		List<String> list = new ArrayList<String>();
		Cursor cursor = this.db.query(TABLE_NAME, new String[] { "name" },
				"name = '" + cinemaName + "'", null, null, null, "name desc");
		if (cursor.moveToFirst()) {
			do {
				list.add(cursor.getString(0));
			} while (cursor.moveToNext());
		}
		
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		
		if (list.size() == 1) {
			exists = true;
		}
			
		return exists;
	}
	
}
